﻿using Castle.Core.Logging;
using Dapper;
using Newtonsoft.Json;
using Serilog;
using Serilog.Core;
using SyncWayBill.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Volo.Abp.DependencyInjection;

namespace SyncWayBill.Service
{
    /// <summary>
    /// 推送运网运单、码单
    /// </summary>
    public class SendLoadService : ITransientDependency
    {
        private ConnectionService _connectionService;

        public SendLoadService(ConnectionService connectionService)
        {
            _connectionService = connectionService;

        }
        /// <summary>
        /// 推送运单
        /// </summary>
        public void SendWaybill()
        {
            using (var conn = _connectionService.GetConnection())
            {
                conn.Open();

                List<WaybillListDto> waybillList = SqlMapper.Query<WaybillListDto>(conn, this.GetWaybillSql()).ToList();
                string createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                foreach (var waybill in waybillList)
                {
                    try
                    {
                        IDbTransaction transaction = conn.BeginTransaction();

                        SendYwLoadingDto sendWaybill = new SendYwLoadingDto();
                        sendWaybill.waybillList = new List<WaybillListDto>() { waybill };
                        string waybillPar = JsonConvert.SerializeObject(sendWaybill);

                        string sendWaybillResultStr = HttpHelpr.Post(_connectionService.GetSendLoadingUrl(), waybillPar);

                        YWResult<List<WaybillListDto>> sendYwWaybillResult = JsonConvert.DeserializeObject<YWResult<List<WaybillListDto>>>(sendWaybillResultStr);
                        int sendStatus = sendYwWaybillResult.code == "200" ? 1 : 2;//1=同步成功  2=同步失败

                        conn.Execute(this.GetInsertWaybillSync(), new
                        {
                            code = waybill.billNo,
                            parmaeters = waybillPar,
                            ywResult = sendWaybillResultStr,
                            status = 1,
                            createTime = createTime,
                            sendStatsus = sendStatus,
                            sendUrl = _connectionService.GetSendLoadingUrl(),
                            amId = waybill.tihuoWaybillId

                        }, transaction);//插入推送记录
                        long tmsWaybillId = 0;
                        if (sendStatus == 1 && sendYwWaybillResult.data != null && sendYwWaybillResult.data.Count > 0)
                        {
                            tmsWaybillId = sendYwWaybillResult.data[0].tmsWaybillId;

                        }
                        conn.Execute("update YDGL_ASSEMBLE_MESSAGE set IS_SEND_YWLODIING=1,YW_YD_ID=:tmsWaybillId where ID = :amId", new
                        {
                            tmsWaybillId = tmsWaybillId,
                            amId = waybill.tihuoWaybillId
                        }, transaction);//修改推送状态
                        transaction.Commit();

                        if (sendYwWaybillResult.code == "200")
                        {
                            this.sendMd(waybill, tmsWaybillId, conn);//推送码单

                        }
                    }
                    catch (Exception e)
                    {
                        Log.Logger.Error("推送运单失败====》", e);

                    }

                }
            }

        }
        /// <summary>
        /// 推送码单
        /// </summary>
        /// <param name="waybill"></param>
        /// <param name="tmsWaybillId"></param>
        private void sendMd(WaybillListDto waybill, long tmsWaybillId, IDbConnection conn)
        {
            try
            {
                IDbTransaction transaction = conn.BeginTransaction();
                SendMdDto sendMdData = new SendMdDto();
                sendMdData.tmsWaybillId = tmsWaybillId;
                sendMdData.tihuoWaybillId = waybill.tihuoWaybillId;
                sendMdData.putoutStackingList = conn.Query<MdDto>(this.GetMdSql(), new
                {
                    ydId = waybill.xcWaybillId,
                    billNo = waybill.billNo
                }).ToList();//查询码单
                if (!sendMdData.putoutStackingList.Any())
                {
                    return;
                }
                foreach (var md in sendMdData.putoutStackingList)
                {
                    List<MdMats> mdMatsList = conn.Query<MdMats>(this.GetMdMats(), new { mdId = md.mdId }).ToList();//查询码单材料
                    md.mats = mdMatsList;
                }
                string mdPar = JsonConvert.SerializeObject(sendMdData);
                string mdSendResultStr = HttpHelpr.Post(_connectionService.GetSendMdUrl(), mdPar);
                YWResult<object> mdSendResult = JsonConvert.DeserializeObject<YWResult<object>>(mdSendResultStr);
                int mdSendStatus = mdSendResult.code == "200" ? 1 : 2;

                conn.Execute(this.GetInsertWaybillSync(), new
                {
                    code = waybill.billNo,
                    parmaeters = mdPar,
                    ywResult = mdSendResultStr,
                    status = 1,
                    createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
                    sendStatsus = mdSendStatus,
                    sendUrl = _connectionService.GetSendMdUrl(),
                    amId = waybill.tihuoWaybillId

                }, transaction);//插入推送记录
                transaction.Commit();
            }
            catch (Exception e)
            {
                Log.Logger.Error("推送码单失败====》", e);

            }

        }
        /// <summary>
        /// 推送码单红冲
        /// </summary>
        public void SendMdHc()
        {
            using (var conn = _connectionService.GetConnection())
            {
                conn.Open();
                IDbTransaction transaction = conn.BeginTransaction();
                List<MdChDto> hcList = SqlMapper.Query<MdChDto>(conn, this.GetMdHcSql()).ToList();
                string createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                foreach (var item in hcList)
                {
                    try
                    {
                        string mdPar = JsonConvert.SerializeObject(item);
                        string mdSendResultStr = HttpHelpr.Post(_connectionService.GetSendMdHcUrl(), mdPar);
                        YWResult<object> mdSendResult = JsonConvert.DeserializeObject<YWResult<object>>(mdSendResultStr);
                        int mdSendStatus = mdSendResult.code == "200" ? 1 : 2;

                        conn.Execute(this.GetInsertWaybillSync(), new
                        {
                            code = item.code,
                            parmaeters = mdPar,
                            ywResult = mdSendResultStr,
                            status = 2,
                            createTime = createTime,
                            sendStatsus = mdSendStatus,
                            sendUrl = _connectionService.GetSendMdHcUrl(),
                            amId = item.tihuoWaybillId

                        }, transaction);//插入推送记录
                        conn.Execute("update XSGL_MADAN set IS_SEND_YWHC=1 where ID =:id", new { id = item.mdId }, transaction);//修改码单红冲状态
                        transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        Log.Logger.Error("推送码单红冲失败====》", e);

                    }

                }
            }


        }
        /// <summary>
        /// 重发
        /// </summary>
        public void RegSend()
        {
            using (var conn = _connectionService.GetConnection())
            {
                List<YdglWaybillSync> list = SqlMapper.Query<YdglWaybillSync>(conn, "select * from YDGL_WAYBILL_SYNC where SEND_STATUS=0 and rownum<=20").ToList();
                foreach (var item in list)
                {
                    string resutlStr = "";
                    int sendStatus = 3;
                    try
                    {
                        if (item.SEND_URL.Contains("rest/tms/tmsLoadingManage/tihuoWay/executeLoading"))
                        {
                            resutlStr = HttpHelpr.Post(_connectionService.GetSendLoadingUrl(), item.PARMAETERS);
                            YWResult<List<WaybillListDto>> result = JsonConvert.DeserializeObject<YWResult<List<WaybillListDto>>>(resutlStr);
                            if (result.code == "200")
                            {
                                long tmsWaybillId = 0;
                                if (result.data != null && result.data.Count > 0)
                                {
                                    tmsWaybillId = result.data[0].tmsWaybillId;
                                }
                                sendStatus = 1;
                                SendYwLoadingDto waybill = JsonConvert.DeserializeObject<SendYwLoadingDto>(item.PARMAETERS);
                                this.sendMd(waybill.waybillList[0], tmsWaybillId, conn);

                            }
                        }
                        else
                        {
                            resutlStr = HttpHelpr.Post(item.SEND_URL, item.PARMAETERS);
                            YWResult<object> result = JsonConvert.DeserializeObject<YWResult<object>>(resutlStr);
                            if (result.code == "200")
                            {
                                sendStatus = 1;
                            }
                        }


                    }
                    catch (Exception ex)
                    {
                        sendStatus = 2;
                        Log.Logger.Error("重发====》", ex);

                    }
                    conn.Execute("update YDGL_WAYBILL_SYNC set SEND_STATUS=:sendStatus,YW_RESULT=:result where ID=:id", new { sendStatus = sendStatus, id = item.ID, result = resutlStr });

                }
            }

        }
        /// <summary>
        /// 获取码单红冲sql
        /// </summary>
        /// <returns></returns>
        private string GetMdHcSql()
        {
            string hcSql = @"select am.YW_YD_ID as tmsWaybillId, am.ID as tihuoWaybillId,md.ID as mdId,md.MADAN_NUMBER as code
                                from YDGL_ASSEMBLE_MESSAGE am
                                         inner join XSGL_MADAN md on am.SOURCE_CODE = md.BILL_NUMBER and am.DELIVERY_ID = md.ORDER_ID
                                where md.MADAN_STATUS = '20'
                                  and nvl(md.IS_SEND_YWHC, 0) = 0
                                  and am.YW_YD_ID >0
                                  and rownum <= 20";
            return hcSql;
        }
        /// <summary>
        /// 获取插入推送记录sql
        /// </summary>
        /// <returns></returns>
        private string GetInsertWaybillSync()
        {
            string syncSql = @"insert into YDGL_WAYBILL_SYNC(CODE, PARMAETERS, YW_RESULT, STATUS, CREATE_TIME, SEND_STATUS, SEND_URL, AM_ID)
                                values (:code, :parmaeters, :ywResult, :status, :createTime, :sendStatsus, :sendUrl,:amId)";
            return syncSql;
        }
        /// <summary>
        /// 获取码单材料
        /// </summary>
        /// <returns></returns>
        private string GetMdMats()
        {
            string mdMatsSql = @"select nvl(MATERIAL_NUMBER, 'A0001') as matId,
                                   nvl(QUANTITY, 1) as unitCount,
                                   nvl(WEIGHT, 0) as netWeight
                            from XSGL_MADAN_ITEMS
                            where MADAN_ID = :mdId";
            return mdMatsSql;
        }
        /// <summary>
        /// 查询码单sql
        /// </summary>
        /// <returns></returns>
        private string GetMdSql()
        {
            string mdSql = @"select '西昌钢钒'                 as factoryName,
                               c.TRANS_MODE           as trnpModeCode,
                               c.FIRST_CNSG_USER_NAME as consignName1,
                               c.LAST_CNSG_USER_NAME    as consignNameFin,
                               c.FIRST_CNSG_ADDRESS_NAME as deliveryPlaceName,
                               c.LAST_CNSG_ADDRESS_NAME as finUserName,
                               md.CONTRACT_NUMBER     as orderItemNum,
                               md.MADAN_NUMBER        as putoutStackingId,
                               '外销'                   as putoutType,
                               nvl(md.N_TOT_DLV,0)           as actCount,
                               nvl(md.WT_NET_DLV,0)          as actNetWeight,
                               to_char(TO_DATE(md.DELIVERY_CREAT_TIME,'yyyyMMddHH24miss'),'yyyymmdd hh24:mi:ss') as actPutoutDate,
                               md.PROD_DSCR           as productName,
                               md.CAR_NUMBER          as vehiceId,
                               md.CAR_NUMBER          as facVehicleId,
                               md.ID                  as mdId
                        from XSGL_MADAN md
                                 left join XSGL_CONTRACT_DETAIL c on md.CONTRACT_NUMBER = c.ORDER_NO
                        where md.ORDER_ID = :ydId
                          and md.BILL_NUMBER = :billNo and md.MADAN_STATUS='2'";
            return mdSql;
        }
        /// <summary>
        /// 查询运单sql
        /// </summary>
        /// <returns></returns>
        private string GetWaybillSql()
        {
            string waybillSql = @"select *
                                    from (select nvl(sum(s.ENTRUCK_NUM), 0)  as weight,
                                                 am.YW_PLAN_ID               as shipmentId,
                                                 note.DRIVER_PHONE           as phone,
                                                 note.CAR_NO                 as carNum,
                                                 am.ID                       as tihuoWaybillId,
                                                 nvl(sum(s.DISPATCH_NUM), 0) as dispatchWeight,
                                                 note.ID                     as xcWaybillId,
                                                 am.SOURCE_CODE              as billNo,
                                                 substr(note.ENTRUCK_DATE,0,19)            as loadingTime
                                          from YDGL_DELIVERY_NOTE note
                                                   inner join YDGL_ASSEMBLE_MESSAGE am on note.ID = am.DELIVERY_ID
                                                   inner join YDGL_DELIVERY_NOTE_SUB s on am.ID = s.ASSEMBLE_ID
                                                   inner join XSGL_BILL_INFO bill on am.SOURCE_CODE = bill.BILL_NO
                                          where note.STATUS >= 20
                                            and am.YW_PLAN_ID is not null
                                            and nvl(am.IS_SEND_YWLODIING, 0) = 0
                                          group by am.YW_PLAN_ID, note.DRIVER_PHONE, am.ID, note.CAR_NO, note.ID, am.SOURCE_CODE,note.ENTRUCK_DATE)
                                    where rownum <= 50";
            return waybillSql;
        }
    }
}
